package com.fenghongzhang.day019;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private ListView musiclist;
    private Button pause;
    private Button pre;
    private Button next;
    private Button restart;
    private Button model;

    //播放的数据源下标
    private int index;

    //播放模式
    private int playModle = 0;
    private List<Music> list;
    private SeekBar seekbar;

    private Timer timer;
    private  MediaPlayer mediaPlayer ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        list = new ArrayList<>();
        mediaPlayer = new MediaPlayer();

        /**
         * 数据源-> sd
         * 1,上传sd -> 重启. ->代码刷新
         * 2,uri 去取 -> 清单授权,-动态.
         * 3,list集合.
         */

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},999);
        }else{
            //
            list = MusicUtil.getMusics(this);
            MusicAdapter musicAdapter = new MusicAdapter(list, this);
            musiclist.setAdapter(musicAdapter);
        }


        musiclist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                play(position);
            }
        });


        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    //播放
    private void play(int position) {
        //重置
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(list.get(position).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                    seekbar.setMax(mediaPlayer.getDuration());
                }
            });

            //播放完成回调
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //根据模式选择下一首的播放逻辑
                    /**
                     * swit(值){
                     * 随机
                     * 否则
                     * 顺序
                     * 否则
                     * 单曲
                     */
                    switch (playModle){
                        case MusicUtil.ORDER:
                            index++;
                            if(index >= list.size() -1){
                                index = 0;
                            }
                            break;
                        case MusicUtil.SINGLE:

                            break;
                        case MusicUtil.RANDOM:
                            index = new Random().nextInt(list.size());
                            break;
                    }
                    play(index);

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (timer != null){
            timer.cancel();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
               seekbar.setProgress(mediaPlayer.getCurrentPosition());
            }
        },0,1000);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 999 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //
            list = MusicUtil.getMusics(this);
            MusicAdapter musicAdapter = new MusicAdapter(list, this);
            musiclist.setAdapter(musicAdapter);
        }else{

        }
    }

    private void initView() {
        seekbar = (SeekBar) findViewById(R.id.seekbar);
        musiclist = (ListView) findViewById(R.id.musiclist);
        pause = (Button) findViewById(R.id.pause);
        pre = (Button) findViewById(R.id.pre);
        next = (Button) findViewById(R.id.next);
        restart = (Button) findViewById(R.id.restart);
        model = (Button) findViewById(R.id.model);
    }

    public void pause(View view) {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
        }
    }

    public void restart(View view) {
        mediaPlayer.start();
    }

    //上一首
    public void pre(View view) {
        index--;
        if(index <= 0){
            index = 0;
        }
        //播放
        play(index);
    }

    //下一首(点击)
    public void next(View view) {
        playNext();
    }

    private void playNext() {
        index++;
        if(index >= list.size() -1){
            index = 0;
        }
        //播放
        play(index);
    }


    //切换播放模式-> 就是换下标
    public void model(View view) {
        final PopupWindow popupWindow = new PopupWindow();
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);

        TextView single = inflate.findViewById(R.id.single);
        single.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Toast.makeText(MainActivity.this, "单曲播放", Toast.LENGTH_SHORT).show();
                playModle = MusicUtil.SINGLE;
            }
        });

        TextView order = inflate.findViewById(R.id.order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Toast.makeText(MainActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                playModle = MusicUtil.ORDER;
            }
        });

        TextView random = inflate.findViewById(R.id.random);
        random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Toast.makeText(MainActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                playModle = MusicUtil.RANDOM;
            }
        });
        popupWindow.setContentView(inflate);


        popupWindow.setOutsideTouchable(true);

        popupWindow.showAsDropDown(model,0,-300);
    }
}
